#!/usr/bin/env python
# coding:utf-8

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email.header import Header


def mail(subject, content):
    my_sender = '32000369@qq.com'  # 发件人邮箱账号
    my_pass = 'asdf2wsx'  # 发件人邮箱密码
    my_user = '15300876878@163.com'  # 收件人邮箱账号
    ret = True
    try:
        msg = MIMEText(content, 'plain', 'utf-8')
        msg['From'] = formataddr(["Robin", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['To'] = formataddr(["Robin", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        msg['Subject'] = subject  # 邮件的主题，也可以说是标题

        server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
        ret = False
        print ("邮件发送失败")
    return ret


def mail2(subject, content, receiver_list):
    my_sender = '32000369@qq.com'  # 发件人邮箱账号
    my_pass = 'asdf3edc'  # 发件人邮箱密码
    my_pass = 'gwywjrbihhvtbiad'
    my_user = '15300876878@163.com'  # 收件人邮箱账号
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['From'] = formataddr(["Robin", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    # to_list = []
    # for i in receiver_list:
    #     to_list.append([i,i])
    # msg['To'] = formataddr(to_list)  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['To'] = ','.join(receiver_list)
    msg['Subject'] = subject  # 邮件的主题，也可以说是标题

    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender, receiver_list, msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 关闭连接

def mail3(subject, content, file_list, receiver_list):
    my_sender = '32000369@qq.com'  # 发件人邮箱账号
    my_pass = 'gwywjrbihhvtbiad'
    msg = MIMEMultipart()
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    msg['From'] = formataddr(["Robin", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = ','.join(receiver_list)
    msg['Subject'] = subject  # 邮件的主题，也可以说是标题


    for file in file_list:
        [file_path,file_name] = file
        att = MIMEText(open(file_path,'rb').read(),'base64','utf-8')
        att['Content-Type'] = 'application/octet-stream'
        att.add_header('Content-Disposition', 'attachment', filename=file_name)
        msg.attach(att)

    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender, receiver_list, msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 关闭连接